package controllers;

import play.*;
import play.cache.Cache;
import play.data.validation.Valid;
import play.db.jpa.Blob;
import play.i18n.Lang;
import play.libs.Crypto;
import play.libs.Images;
import play.libs.Mail;
import play.libs.OAuth2;
import play.mvc.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import org.apache.commons.io.IOUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import br.com.nordestefomento.jrimum.bopepo.BancoSuportado;
import br.com.nordestefomento.jrimum.bopepo.Boleto;
import br.com.nordestefomento.jrimum.bopepo.view.BoletoViewer;
import br.com.nordestefomento.jrimum.domkee.comum.pessoa.endereco.CEP;
import br.com.nordestefomento.jrimum.domkee.comum.pessoa.endereco.Endereco;
import br.com.nordestefomento.jrimum.domkee.comum.pessoa.endereco.UnidadeFederativa;
import br.com.nordestefomento.jrimum.domkee.financeiro.banco.febraban.Agencia;
import br.com.nordestefomento.jrimum.domkee.financeiro.banco.febraban.Carteira;
import br.com.nordestefomento.jrimum.domkee.financeiro.banco.febraban.Cedente;
import br.com.nordestefomento.jrimum.domkee.financeiro.banco.febraban.ContaBancaria;
import br.com.nordestefomento.jrimum.domkee.financeiro.banco.febraban.NumeroDaConta;
import br.com.nordestefomento.jrimum.domkee.financeiro.banco.febraban.Sacado;
import br.com.nordestefomento.jrimum.domkee.financeiro.banco.febraban.SacadorAvalista;
import br.com.nordestefomento.jrimum.domkee.financeiro.banco.febraban.TipoDeTitulo;
import br.com.nordestefomento.jrimum.domkee.financeiro.banco.febraban.Titulo;
import models.*;
public class Experiencias extends Application {
	
			
public static void index(Experiencia experiencia) {
	
		render(experiencia);
	}

		
		public static void addBar(Experiencia bar) {
			bar.exp_descricao = "asdhashdasd";
	        bar.save();
	        bar = new Experiencia();
	        //cadastrar(bar);
	    }
		
		  public static void listBars() {
			 Email a = new Email();
		        renderJSON(a);
		    }
	
    
    
    public static void cadastrarExperiencia(Experiencia experiencia) {
    	File outputFile = null;
    	experiencia.exp_estado_publicado="não";
    	    Blob usu_ima = experiencia.exp_ima ;
    	     experiencia.save();
            if (usu_ima != null){ 
            	
             outputFile = Play.getFile("/public/images/capa/" + experiencia.exp_titulo+experiencia.exp_codigo + ".jpg");
            Images.resize(usu_ima.getFile(), outputFile, 1700, 450);
            experiencia.exp_caminho_ima = "http://speakrs.me/public/images/capa/" + experiencia.exp_titulo+experiencia.exp_codigo + ".jpg";
           
            }
            
            usu_ima = experiencia.exp_ima_home ;
            experiencia.save();
           if (usu_ima != null){ 
   			
            outputFile = Play.getFile("/public/images/home/" + experiencia.exp_titulo+experiencia.exp_codigo + ".jpg");
           Images.resize(usu_ima.getFile(), outputFile, 300, 220);
           experiencia.exp_caminho_ima_home = "http://speakrs.me/public/images/home/" + experiencia.exp_titulo+experiencia.exp_codigo + ".jpg";

  	   
           }
           if (  experiencia.exp_link_video != null)
         experiencia.exp_link_video = experiencia.exp_link_video.replace("http:", "").replace("watch?v=", "embed/");
          experiencia.save();
    	SimpleEmail mail = new SimpleEmail();
    	try {
    		mail.setFrom("odilionoronha@gmail.com");
    		mail.addTo("info@speakrs.me");
    		mail.setSubject("Inscricao Speakrs");
	    	mail.setMsg("Bem vindo ao Speakrs, em breve entraremos em contato e avaliaremos a sua experiencia! ");
	    	Mail.send(mail); 
		} catch (EmailException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	Speakr speakr = new Speakr();
    	
    	Speakrs.perfil(speakr);
   }
    
    public static void reserve(Experiencia exp) {
    	   
   	 render(exp);
   }
    
    public static void cadastrarReserva(Reserva reserva) {
    	int id = params.get("experiencia.exp_codigo", Integer.class);
    	Experiencia exp = Experiencia.findById(id);
    	//reserva.res_boleto = boleto();
    	/*reserva.save();
    	SimpleEmail mail = new SimpleEmail();
    	try {
    		mail.setFrom("odilionoronha@gmail.com");
    		mail.addTo(reserva.res_email);
    		mail.setSubject("Reserva de Experiencia ");
	    	mail.setMsg("Bem vindo ao Speakrs, em breve entraremos em contato e avaliaremos a sua experiencia! ");
	    	Mail.send(mail); 
		} catch (EmailException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
    	reserve(exp);
      }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
public static void validation() throws Exception {
		
		Logger.info("validation");
		
		// creation de l'url a envoyé à paypal pour vérification
		//on recupere les parametres de la requetes POST
		String str = "cmd=_notify-validate&" + params.get("body");
		Logger.info(str);
		
		//création d'une connection à la sandbox paypal
		URL url = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr");
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		
		//envoi de la requête
		PrintWriter out = new PrintWriter(connection.getOutputStream());
		out.println(str);
		out.close();

		//lecture de la réponse
		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String result = in.readLine();
		in.close();
		
		// assign posted variables to local variables
		String itemName = params.get("item_name");
		String itemNumber = params.get("item_number");
		String paymentStatus = params.get("payment_status");
		String paymentAmount = params.get("mc_gross");
		String paymentCurrency = params.get("mc_currency");
		String txnId = params.get("txn_id");
		String receiverEmail = params.get("receiver_email");
		String payerEmail = params.get("payer_email");

		//check notification validation
		if("VERIFIED".equals(result)) {
			if ("Completed".equals(paymentStatus)) {
				// on vérife que la txn_id n'a pas été traité précédemment
				PaypalTransaction paypalTransaction = PaypalTransaction.findByTrxId(txnId);
				// si aucune transaction en base ou si transaction mais en status invalide
				// on traite la demande
				if (paypalTransaction == null 
						|| (paypalTransaction != null && PaypalTransaction.TrxStatusEnum.INVALID.equals(paypalTransaction.status))) {
					// on vérifie que receiver_email est votre adresse email
					// a remplacer par l'adresse mail du vendeur
					if ("seller@paypalsandbox.com".equals(receiverEmail)) {
						// vérifier que paymentAmount (EUR) et paymentCurrency (prix du produit vendu) sont corrects
						Logger.info("Transaction OK");
						//sauvegarde la trace de la transaction paypal en base
						new PaypalTransaction(itemName, itemNumber, paymentStatus, paymentAmount, paymentCurrency, txnId, receiverEmail, payerEmail,PaypalTransaction.TrxStatusEnum.VALID).save();
					} else {
						// Mauvaise adresse email paypal
						Logger.info("Mauvaise adresse email paypal");
					}
				} else {
					// ID de transaction déjà utilisé
					Logger.info("La transaction a déjà été traité");
				}
			} else {
				// Statut de paiement: Echec
				Logger.info("Statut de paiement: Echec");
			}
		} else if("INVALID".equals(result)) {
			Logger.info("Invalide transaction");
			new PaypalTransaction(itemName, itemNumber, paymentStatus, paymentAmount, paymentCurrency, txnId, receiverEmail, payerEmail,PaypalTransaction.TrxStatusEnum.INVALID).save();
		} else {
			Logger.info("Erreur lors du traitement");
		}
    }
	
	/** Success payment */
	public static void success(){
		Logger.info("success");
		render();
	}
	
	/** home page */
	public static void buy(){
		Logger.info("buy");
		render();
	}
	
	/** fail payment */
	public static void fail(){
		Logger.info("fail");
		render();
	}
}